package redis_handler

import (
	"bufio"
	"fmt"
	logger "gitee.com/zaper/private-logger"
	"gitee.com/zaper/redis-service/constant"
	"io"
	"os"
	"path/filepath"
	"strings"
)

func RedisConfHandler(ip, port string) bool {
	redisConf := filepath.Join(constant.RedisWorkspaceValue, "redis.windows-service_tmp.conf")
	file, err := os.Open(redisConf)
	defer file.Close()
	if err != nil {
		logger.Errorf("open redis_tmp file fail, err is %s", err)
		return false
	}
	redisConf = filepath.Join(constant.RedisWorkspaceValue, "redis.windows-service.conf")
	oFile := outFile(redisConf)
	defer oFile.Close()
	if oFile == nil {
		logger.Errorf("get conf file fail, err is %s", err)
		return false
	}
	r := bufio.NewReader(file)
	w := bufio.NewWriter(oFile)
	for {
		_ = w.Flush()
		line, _, err := r.ReadLine()
		if err == io.EOF {
			return true
		}
		lineStr := strings.TrimSpace(string(line))
		if lineStr == "" {
			_, err = w.Write([]byte(fmt.Sprintf("\n")))
			continue
		}
		if strings.HasPrefix(lineStr, "#") {
			_, err = w.Write([]byte(fmt.Sprintf("%s\n", lineStr)))
			continue
		}
		index := strings.Index(lineStr, " ")
		key := strings.TrimSpace(lineStr[:index])
		values := strings.TrimSpace(lineStr[index+1:])
		if key == "port" {
			values = port
		}
		if key == "bind" {
			values = fmt.Sprintf("%s %s", ip, "-::1")
		}
		lineStr = fmt.Sprintf("%s %s\n", key, values)
		_, err = w.Write([]byte(lineStr))
		if err != nil {
			_, err = w.Write([]byte(lineStr))
			if err != nil {
				logger.Errorf("write redis conf fail, err is %s", err)
				return false
			}
		}
	}
}

func outFile(redisConf string) *os.File {
	_, err := os.Stat(redisConf)
	if err == nil {
		err = os.Remove(redisConf)
		if err != nil {
			err = os.Remove(redisConf)
		}
		if err != nil {
			logger.Errorf("Remove file fail, err is %s", err)
			return nil
		}
	}
	file, err := os.OpenFile(redisConf, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		logger.Errorf("open conf file fail, err is %s", err)
		return nil
	}
	return file
}
